<?php

namespace App\Repositories\Ca;

use App\Facade\AppContext;
use App\Models\BaseModel;
use App\Models\Ca\Customer;
use App\Models\Ca\CustomerExtend;
use App\Models\Ca\Disease;
use App\Models\Ca\Visit;
use App\Models\System\Department;
use App\Models\System\Group;
use App\Repositories\BaseRepository;
use App\Utils\Output;
use App\Utils\QueryHelper;

class VisitRepository extends BaseRepository
{

    /**
     * 分页查询
     * @param array $params
     * @return Output
     */
    function adminPager(array $params)
    {
        extract($params);
        $query = Customer::query()->where('ca__customers.hospital_id', '=', AppContext::hospitalId());
        $query->join('ca__visits', 'ca__visits.customer_id', '=', 'ca__customers.id');
        if (!empty($keyword)) {
            QueryHelper::like($query, 'ca__customers.name|ca__customers.id|ca__customers.mobile', $keyword);
        }
        if (!empty($date_range)) {
            list($start, $end) = explode(' ~ ', $date_range);
            $query->whereBetween('ca__customers.created_at', [$start, $end]);
        }
        if (!empty($department_id)) {
            if (!empty($disease_id)) {
                //具体的疾病
                $query->whereHas('diseases', function ($query) use ($disease_id) {
                    $query->where('disease_id', '=', $disease_id);
                });
            } else {
                //科室
                $query->whereHas('diseases', function ($query) use ($department_id) {
                    $disease = Disease::find($department_id);
                    $query->join('ca__diseases', 'ca__diseases.id', '=', 'ca__customer_diseases.disease_id');
                    $query->where('ca__diseases.code', 'like', $disease['code'] . '%');
                });
            }
        }
        if (!empty($custom_service_id)) {
            $query->where('ca__customers.custom_service_id', '=', $custom_service_id);
        }
        $query->join('system__users', 'system__users.id', '=', 'ca__visits.user_id');
        //权限
        if (AppContext::groupCode() == Group::CALLER) {
            if (AppContext::can('ca/customer', 'can_department') && AppContext::userInfo('department_id') > 0) {
                //查看子部门数据
                $query->leftJoin('system__departments as medical_department', 'medical_department.id', '=', 'system__users.department_id');
                $department = Department::find(AppContext::userInfo('department_id'));
                $query->where('medical_department.code', 'like', $department['code'] . '%');
            } else {
                $query->where('ca__visits.user_id', '=', AppContext::userId());
            }

        } elseif (AppContext::groupCode() == Group::CUSTOM_SERVICE) {
            if (AppContext::can('ca/customer', 'can_department') && AppContext::userInfo('department_id') > 0) {
                //查看子部门数据
                $query->leftJoin('system__departments as cs_department', 'cs_department.id', '=', 'system__users.department_id');
                $department = Department::find(AppContext::userInfo('department_id'));
                $query->where('cs_department.code', 'like', $department['code'] . '%');
            } else {
                $query->where('ca__visits.user_id', '=', AppContext::userId());
            }
        }
        $totalQuery = clone $query;
        $total = $totalQuery->count();


        $query->leftJoin('system__areas as province', 'province.id', '=', 'ca__customers.province_id');
        $query->leftJoin('system__areas as city', 'city.id', '=', 'ca__customers.city_id');
        $query->select(
            'ca__visits.id',
            'ca__visits.customer_id',
            'ca__visits.created_at',
            'ca__visits.content',
            'ca__visits.next_time',
            'ca__visits.supervisor_annotate',
            'ca__customers.name',
            'system__users.name as user_name',
            'province.name as province_name',
            'city.name as city_name'
        );
        $lis = $this->setParams($query, $params, ['ca__visits.id' => 'desc']);
        $extendMany = CustomerExtend::getMany();
        foreach ($lis as $item) {
            $extendMany->add($item['customer_id']);
        }
        $extendMany->query(['id', 'disease_data']);
        foreach ($lis as $item) {
            $item['area_name'] = $item['province_name'] . ' ' . $item['city_name'];
            $disease_data = $extendMany->getField($item['customer_id'], 'disease_data', []);
            $diseases = [];
            foreach ($disease_data as $datum) {
                $diseases[] = $datum['name'];
            }
            $item['diseases'] = implode('、', $diseases);
        }
        return Output::pager($lis, $total);
    }

    function getModel(): BaseModel
    {
        return new Visit();
    }
}